/**
 * Created by Tuffy on 16/1/18.
 */
'use strict';

angular.module('starter.controllers')
//酒店拜访记录列表
.controller('HotelVisitCtrl', ['$scope','$rootScope', '$timeout', '$cordovaActionSheet', '$ionicModal', '$state', 'VisitService','$cordovaToast', 'ionicMaterialMotion', 'ionicMaterialInk', '$ionicLoading',
function($scope,$rootScope, $timeout, $cordovaActionSheet, $ionicModal, $state, VisitService,$cordovaToast, ionicMaterialMotion, ionicMaterialInk, $ionicLoading) {

    $scope.visit = {
        search: {
            value:'',
            filter:{},
            doAct:function(){
                if(this.timer){
                    $timeout.cancel(this.timer);
                }
                this.timer = $timeout(function(){
                    $scope.visit.refresh();
                },500);
            }
        },
        page: {
            pageNum:0,
            pageSize:10
        },
        loaded:true,
        data:[],
        loadData:function(okFunc){
            var _this = this,
                params = {
                    hotelId: $scope.$parent.hotelId,
                    pageNum:_this.page.pageNum,
                    pageSize:_this.page.pageSize
                };

            _this.loaded = false;
            VisitService.findHotelVisitList(params)
                .success(function(res){
                    if(res.success){
                        if(typeof (okFunc) == 'function'){
                            okFunc();
                        }
                        var _data = res.attribute.rows;
                        if(!_data || _data.length<=0){
                            _this.moreDataCanBeLoaded = false;
                            $cordovaToast.showShortBottom('已加载到尾页');
                            return;
                        }
                        _this.data = _this.data.concat(_data);
                    }else{

                        console.log('加载失败');
                    }
                }).error(function(error){

                console.log(error);
            }).finally(function(){
                // $ionicLoading.hide();
                _this.loaded = true;
                if(_this.data.length<_this.page.pageSize){
                    _this.moreDataCanBeLoaded = false;
                }
                $scope.$broadcast('scroll.refreshComplete');
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $timeout(function() {
                    ionicMaterialMotion.fadeSlideIn();
                }, 200);

                $timeout(function() {
                    ionicMaterialInk.displayEffect();
                }, 1000);
            });
        },
        moreDataCanBeLoaded:true,
        loadMore:function(){
            this.page.pageNum++;
            this.loadData();
        },
        refresh:function(){
            var _this = this;
            _this.page.pageNum = 1;
            _this.loadData(function(){
                _this.data = [];
            });
        }
    } ;

    /**
     * 监听添加完成操作事件
     */
    $rootScope.$on('EDIT_COMPLETE', function (event,result) {
        var visit = result['HotelVisitEdit'];
        if(visit){
            $scope.visit.refresh();
        }
    });

    //  查看详细
    $scope.showDetail = function(visit) {
        $state.go('app.hotel-visit-detail', {id: visit.id});
    };

    $scope.visit.refresh();

}])
//酒店拜访记录详情
.controller('HotelVisitDetailCtrl', ['$rootScope','$scope', '$state','VisitService','HotelService','$filter','$ionicPopup','$cordovaToast','$ionicLoading',
    function($rootScope,$scope, $state,VisitService,HotelService,$filter,$ionicPopup,$cordovaToast,$ionicLoading) {
        var visitId = $state.params.id,
            type = 'HotelVisitEdit',
            isToday = function(millisec){
                var today = new Date(),
                    d = new Date(millisec);
                if(d.setHours(0,0,0,0) == today.setHours(0,0,0,0)){
                    return true;
                } else {
                    return false;
                }
            },
            roleDict = {
                1:'老板',
                2:'前台'
            },
            init = function(){
                loadVisitData();

                // findContacts();
                //设置字典
                for(var key in $scope.dict){
                    findDict(key);
                }
                $scope.dict['purchase_intention'] = {
                    'T':'有意向',
                    'F':'无意向'
                };
                $scope.dict['T_F'] = {
                    'T':'是',
                    'F':'否'
                };
            },format = function(data){
                data.visitDate = new Date();
                data.maxDate = $filter('date')(data.visitDate,'yyyy-MM-dd');
                data.hotelName = $rootScope.EDIT_HOTEL.hotelName;
                data.visitHotelId = $rootScope.EDIT_HOTEL.id;
                return data;
            },
            formatSave = function(data){
                data.visitTime = $filter('date')(data.visitDate,'yyyyMMddHHmmss');
                if($scope.visitReasonList){
                    data.visitFailReason = JSON.stringify($scope.visitReasonListSave);
                }else {
                    data.visitFailReason = null;
                }
                delete data.visitDate;
                return data;
            },
            formatContact = function(data){
                $scope.hotelContacts = [];
                for(var i in data){
                    var contact = data[i],
                        id=contact.id,
                        name=contact.name?contact.name:'',
                        role=roleDict[contact.roleId];
                    // $scope.hotelContacts.push({
                    //     id:name,
                    //     name:name + '  '+role
                    // });
                    // if(!$scope.visit.hotelContacts){
                    //     $scope.visit.hotelContacts = name;
                    // }
                    $scope.dict['hotel_contacts'][name] = name + '  '+role;
                }
            },findDict = function(dictName){
                VisitService.findDict(dictName)
                    .success(function(res){
                        if(res.success){
                            $scope.dict[dictName] = res.attribute;
                            if(dictName == "visit_way"){
                                //增加默认值
                                $scope.visit.visitWay = "1";
                            }else if(dictName == "sample_grant"){
                                //增加默认值
                                $scope.visit.sampleGrant = "3";
                            }
                        }else{
                        }
                    })
                    .error(function(error){

                    })
                    .finally(function(){

                    });
            },findContacts = function(){
                HotelService.getContacts({
                        hotelId:$rootScope.EDIT_HOTEL.id,
                        pageNum:1,
                        pageSize:100
                    })
                    .success(function(res){
                        var nullTip = '请先给酒店添加联系人';
                        if(res.success){
                            if(!res.attribute || res.attribute.rows.length<=0){
                                $cordovaToast.showShortBottom(nullTip);
                            }
                            formatContact(res.attribute.rows);
                        }else{
                            $cordovaToast.showShortBottom(nullTip);
                        }
                    })
                    .error(function(error){

                    })
                    .finally(function(){

                    });
            },loadVisitData = function () {
                VisitService.findVisitById(visitId)
                .success(function(data){
                    if (data.success) {
                        $scope.visit = data.attribute;
                    }else{
                        console.log('加载失败');
                    }
                })
                .error(function(error){
                    console.log('加载失败');
                });
            };
        $scope.visit = {};
        $scope.dict = {
            // 'visit_type':{}, //拜访方式
            // 'visit_way':{}, //拜访类型
            'sample_grant':{}, //样品发放
            // 'purchase_intention':{}, //采购意向
            'unvisit_reason':{}, //未采购原因,
            // 'hotel_contacts':{}, //酒店联系人,
            'failure_reason':{}, //失败原因
            // 'T_F': {}
        };
        $scope.showEdit = function () {
            console.log(isToday($scope.visit.createTime));
            return isToday($scope.visit.createTime);
        };
        /**
         * 编辑
         */
        $scope.doEdit = function(){
            if(!$rootScope.EDIT_DATE){
                $rootScope.EDIT_DATE = {};
            }
            $rootScope.EDIT_DATE[type] = _.clone($scope.visit);
            $state.go('app.hotel-visit-edit');
        };
        /**
         * 删除
         */
        $scope.doDelete = function(id){
            $ionicPopup.confirm({
                title: '删除',
                template: '您确定删除吗？',
                cancelText:'取消',
                cancelType:'button-block button-outline button-energized-crm',
                okText: '确定',
                okType: 'button-block button-energized-crm',
            }).then(function(res) {
                if(res) {
                    $ionicLoading.show({
                        template: '删除中...'
                    });
                    VisitService.delete(id)
                    .success(function(data){
                        if (data.success) {
                            $rootScope.$broadcast('EDIT_COMPLETE',{
                                'HotelVisitEdit':{}
                            });
                            $scope.$ionicGoBack();
                            $cordovaToast.showShortBottom('删除成功!');
                        }else{
                            $cordovaToast.showShortBottom('删除失败!');
                        }
                    })
                    .error(function(error){
                        $cordovaToast.showShortBottom('删除失败!');
                    }).finally(function () {
                        $ionicLoading.hide();
                    });
                } else {
                    // console.log('You are not sure');
                }
            });
        };
        $rootScope.$on('EDIT_COMPLETE', function (event,result) {
            var visit = result[type];
            if(visit){
                loadVisitData();
            }
        });
        // 销毁编辑数据
        $scope.$on('$destroy', function() {
            $rootScope.EDIT_DATE[type] && delete $rootScope.EDIT_DATE[type];
        });
        init();
    }])
//拜访记录列表
.controller('VisitCtrl', ['$scope','$rootScope', '$timeout', '$cordovaActionSheet', '$ionicModal', '$state', 'VisitService','$cordovaToast', 'ionicMaterialMotion', 'ionicMaterialInk', '$ionicLoading',
    function($scope,$rootScope, $timeout, $cordovaActionSheet, $ionicModal, $state, VisitService,$cordovaToast, ionicMaterialMotion, ionicMaterialInk, $ionicLoading) {

    $scope.visit = {
        search: {
            value:'',
            filter:{},
            doAct:function(){
                if(this.timer){
                    $timeout.cancel(this.timer);
                }
                this.timer = $timeout(function(){
                    $scope.visit.refresh();
                },500);
            }
        },
        page: {
            pageNum:0,
            pageSize:10,
            total:0
        },
        loaded:true,
        data:[],
        loadData:function(okFunc){
            var _this = this,
                params = {
                    hotelName:this.search.value,
                    pageNum:_this.page.pageNum,
                    pageSize:_this.page.pageSize
                };
                if (_this.search.filter) {
                    params.visit = _this.search.filter.visit;
                    params.visitDay = _this.search.filter.visitDay;
                }
            _this.loaded = false;

            // $ionicLoading.show({
            //     template: '加载中...'
            // });
            VisitService.findVisitList(params)
                .success(function(res){
                    if(res.success){
                        if(typeof (okFunc) == 'function'){
                            okFunc();
                        }
                        var _data = res.attribute.rows;
                        if(!_data || _data.length<=0){
                            _this.moreDataCanBeLoaded = false;
                            $cordovaToast.showShortBottom('已加载到尾页');
                            return;
                        }else if(_data.length==_this.page.pageSize){
                            _this.moreDataCanBeLoaded = true;
                        }
                        _this.data = _this.data.concat(_data);
                    }else{
                        console.log('加载失败');
                    }
                }).error(function(error){
                console.log(error);
            }).finally(function(){
                // $ionicLoading.hide();
                _this.loaded = true;
                if(_this.data.length<_this.page.pageSize){
                    _this.moreDataCanBeLoaded = false;
                }
                $scope.$broadcast('scroll.refreshComplete');
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $timeout(function() {
                    ionicMaterialMotion.fadeSlideIn();
                }, 200);

                $timeout(function() {
                    ionicMaterialInk.displayEffect();
                }, 1000);
            });
        },
        moreDataCanBeLoaded:true,
        loadMore:function(){
            this.page.pageNum++;
            this.loadData();
        },
        refresh:function(){
            var _this = this;
            _this.page.pageNum = 1;
            _this.loadData(function(){
                _this.data = [];
            });
        }
    } ;

    //  查看详细
    $scope.showDetail = function(visit) {
        $rootScope.reportVisit = visit;
        // $state.go('app.chars-visit-detail', {id: visit.id});
        $state.go('app.hotel-visit-detail', {id: visit.id});
    };

    $scope.visit.refresh();

    $scope.isFilter = function () {
        return Object.keys($scope.visit.search.filter).length > 0;
    };

    $rootScope.$on('chars-visit', function(event, data) {
        if (data) {
            if ($rootScope.CHARS_VISIT_DAYS) {
                var visitDayId = '';
                for (var i = 0; i < $rootScope.CHARS_VISIT_DAYS.items.length; i++) {
                    var item = $rootScope.CHARS_VISIT_DAYS.items[i];
                    if (data.visitDay == item.id) {
                        visitDayId = item.value;
                        break;
                    }
                }
            }
            $scope.visit.search.filter = {
                visit: data.charsVisitKey || '',
                visitDay: visitDayId || ''
            };
        } else {
            $scope.visit.search.filter = {
                visit: '',
                visitDay: ''
            };
        }
        $scope.visit.refresh();
    });

}])
.service('VisitService',['CrmHttp','$rootScope',function(CrmHttp,$rootScope){
    var url = '/crm/crm-visit-record/';
    return {
        /**
         * 分销酒店全部数据
         * @param params
         * @returns {*}
         */
        findVisitList: function (params) {
            var act = 'find-report-list';
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },

        /**
         * 分销酒店全部数据
         * @param params
         * @returns {*}
         */
        findHotelVisitList: function (params) {
            var act = 'find-visit-list';
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 获取拜访字典数据
         * @param dictName （visit_type，visit_way）
         * @returns {*}
         */
        findDict:function(dictName){
            var act = 'findValueLabel',
                params = {};
            params['code'] = dictName;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 增加拜访记录
         * @param params
         * @returns {*}
         */
        insert: function (params) {
            var act = 'temporary-save';
            params['visitUser'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 增加拜访失败原因记录
         * @param params
         * @returns {*}
         */
        selectVisitReasonList:function(){
            var act = 'findValueLabelByCode';
            var params ={code:'failure_reason'};
            return CrmHttp.post('/crm/crm-visit-record/' + act, params);
        },
        /**
         * 获取单条拜访记录（报表查询用）
         * @param params
         * @returns {*}
         */
        findReportVisitById: function (visitId) {
            var act = 'findReportVisitById',
                params = {
                    visitId:visitId
                };
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 获取单条拜访记录（单个酒店拜访记录用）
         * @param params
         * @returns {*}
         */
        findVisitById: function (visitId) {
            var act = 'findVisitById',
                params = {
                    visitId:visitId
                };
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        } ,
        /**
         * 删除拜访记录
         * @param params
         * @returns {*}
         */
        delete: function (id) {
            var act = 'delete',
                params = {
                    id:id
                };
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        }
    };
}]);